使用 KMS 將私密資訊加密
Terraform安裝KMS
[key_usage](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/kms_key#key_usage):預期用途
,default是ENCRYPT_DECRYPT
resource "aws_kms_key" "rds" {
description = "KMS key 1"
key_usage = "ENCRYPT_DECRYPT"
deletion_window_in_days = 10
}
resource "aws_kms_alias" "rds" {
name = "alias/aurora"
target_key_id = aws_kms_key.rds.key_id
}
如此就可得到相對應的KMS,記錄一下我們的金鑰ID
```tsx
c0a...
```
藉由KMS獲得加密過的帳密
為了不讓我們的帳密直接進到Git,我們先為帳密各自新建一個檔案叫做username跟password。中間的i-am-username跟i-am-password記得改成自己的帳密
echo -n 'i-am-username' > username
echo -n 'i-am-password' > password
使用CLI獲得相對應的金鑰
aws kms encrypt --key-id c0a3e2... --plaintext fileb://username --output text --query CiphertextBlob --profile backyard --region ap-northeast-1
aws kms encrypt --key-id c0a3e2a... --plaintext fileb://password --output text --query CiphertextBlob
建立 Data Source
將上一步拿到的金鑰放入payload,由於奇怪的符號太多,我們改用 **Heredoc Strings
**的方式放入,詳細參考:https://www.terraform.io/language/expressions/strings
data "aws_kms_secrets" "portal" {
secret {
name = "master_username"
payload = <<-EOT
AQICAHgblt+gCaxL
EOT
}
secret {
name = "master_password"
payload = <<-EOT
AQICAHgblt+gCaxLk
EOT
}
}
參考https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/kms_secrets
我們可以在 RDS的頁面看到username改成我們要的